<template>
  <div class="space-detail-container">
    <!-- 头部工具栏 -->
    <div class="header-toolbar">
      <div class="left-section">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/knowledge' }">知识管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ space.name }}</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="right-section">
        <el-input v-model="searchKeyword" placeholder="搜索文档..." class="search-input" @keyup.enter="quickSearch"
          clearable>
          <template #append>
            <el-button @click="quickSearch">
              <el-icon>
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
        <el-button @click="openAdvancedSearch">
          <el-icon>
            <Search />
          </el-icon>
          高级搜索
        </el-button>
        <el-button type="primary" @click="showCreateDocDialog = true">
          <el-icon>
            <Plus />
          </el-icon>
          新建文档
        </el-button>
        <el-button @click="createFolder">
          <el-icon>
            <FolderAdd />
          </el-icon>
          新建文件夹
        </el-button>
        <el-button @click="showUploadDialog = true">
          <el-icon>
            <Upload />
          </el-icon>
          上传文档
        </el-button>
        <el-button @click="openSpaceSettings">
          空间设置
        </el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧文档树 -->
      <div class="sidebar">
        <div class="space-info">
          <div class="space-icon" :style="{ backgroundColor: space.color || '#409EFF' }">
            {{ space.name ? space.name.charAt(0).toUpperCase() : 'S' }}
          </div>
          <div class="space-details">
            <h3>{{ space.name || '加载中...' }}</h3>
            <p>{{ space.description || '暂无描述' }}</p>
            <div class="space-stats">
              <span>{{ documents.length }} 个文档</span>
              <span>{{ space.members || 1 }} 个成员</span>
            </div>
          </div>
        </div>

        <div class="doc-tree">
          <div class="tree-header">
            <h4>文档结构</h4>
            <div class="tree-actions">
              <el-button size="small" @click="refreshTree">
                <el-icon>
                  <Refresh />
                </el-icon>
              </el-button>
              <el-button size="small" @click="expandAll" title="展开" style="margin-left: 8px;">
                <el-icon>
                  <Plus />
                </el-icon>
              </el-button>
              <el-button size="small" @click="collapseAll" title="收起" style="margin-left: 4px;">
                <el-icon>
                  <Minus />
                </el-icon>
              </el-button>
            </div>
          </div>
          <el-tree ref="documentTreeRef" :data="documentTree" :props="treeProps" node-key="id"
            :expand-on-click-node="false" :default-expanded-keys="expandedKeys" :highlight-current="false"
            @node-click="handleNodeClick" @node-contextmenu="handleNodeRightClick" draggable @node-drop="handleNodeDrop"
            :allow-drop="allowDrop" :allow-drag="allowDrag" class="doc-tree-component" @node-expand="handleNodeExpand"
            @node-collapse="handleNodeCollapse" :key="treeKey">
            <template #default="{ node, data }">
              <div class="tree-node"
                :class="{ 'is-selected': selectedNodeId === (data.type === 'folder' ? 'folder_' + data.id : data.id) }">
                <el-icon v-if="data.type === 'folder'" class="node-icon folder-icon">
                  <Folder />
                </el-icon>
                <el-icon v-else class="node-icon document-icon">
                  <Document />
                </el-icon>
                <span class="node-label" :title="node.label">{{ data.name }}</span>
                <div class="node-actions" v-show="hoveredNodeId === data.id" v-if="!data.isRoot">
                  <el-button size="small" text @click.stop="editDocumentAction(data)" title="编辑">
                    <el-icon>
                      <Edit />
                    </el-icon>
                  </el-button>
                  <el-button size="small" text @click.stop="deleteDocument(data)" title="删除">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                  <el-dropdown @command="handleNodeAction" @click.stop>
                    <el-button size="small" text title="更多">
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-if="data.type === 'folder'"
                          :command="{ action: 'addFolder', data }">新建子文件夹</el-dropdown-item>
                        <el-dropdown-item v-if="data.type === 'folder'"
                          :command="{ action: 'addDocument', data }">新建文档</el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'copy', data }">复制</el-dropdown-item>
                        <el-dropdown-item :command="{ action: 'move', data }">移动</el-dropdown-item>
                        <el-dropdown-item v-if="data.type === 'document'"
                          :command="{ action: 'favorite', data }">收藏</el-dropdown-item>
                        <el-dropdown-item v-if="data.type === 'document'"
                          :command="{ action: 'share', data }">分享</el-dropdown-item>
                        <el-dropdown-item v-if="data.type === 'document'"
                          :command="{ action: 'download', data }">下载</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
            </template>
          </el-tree>
        </div>
      </div>

      <!-- 右侧内容区域 -->
      <div class="content-area">
        <!-- 文档列表视图 -->
        <div v-if="!selectedDocument" class="documents-view">
          <div class="view-header">
            <div class="header-left">
              <h3>文档列表</h3>
              <!-- 当前路径显示 -->
              <span class="current-path-text">
                <span @click="goToFolder('root')" class="breadcrumb-clickable">/根目录</span><span
                  v-if="selectedFolderId && selectedFolderId !== 'root'">/{{ getCurrentFolderName() }}</span>
              </span>
            </div>
            <div class="view-controls">
              <el-select v-model="sortBy" size="small" style="width: 120px;">
                <el-option label="按名称" value="name" />
                <el-option label="按时间" value="time" />
                <el-option label="按大小" value="size" />
              </el-select>
              <el-button-group>
                <el-button :type="viewMode === 'grid' ? 'primary' : ''" @click="viewMode = 'grid'">
                  <el-icon>
                    <Grid />
                  </el-icon>
                </el-button>
                <el-button :type="viewMode === 'list' ? 'primary' : ''" @click="viewMode = 'list'">
                  <el-icon>
                    <List />
                  </el-icon>
                </el-button>
              </el-button-group>
            </div>
          </div>

          <!-- 网格视图 -->
          <div v-if="viewMode === 'grid'" class="documents-grid">
            <div v-for="doc in filteredDocuments" :key="doc.id" class="doc-card" @click="openDocument(doc)">
              <div class="doc-icon">
                <el-icon>
                  <Document />
                </el-icon>
              </div>
              <div class="doc-info">
                <h4>{{ doc.name }}</h4>
                <p class="doc-desc">{{ doc.description || '暂无描述' }}</p>
                <div class="doc-meta">
                  <span class="update-time">{{ formatTime(doc.updatedAt) }}</span>
                  <span class="doc-size">{{ formatSize(doc.size) }}</span>
                </div>
              </div>
              <div class="doc-actions">
                <el-button size="small" text @click.stop="toggleFavorite(doc)">
                  <el-icon>
                    <Star v-if="!doc.isFavorite" />
                    <StarFilled v-else />
                  </el-icon>
                </el-button>
                <el-dropdown @command="(command) => handleDocCommand(command, doc)" @click.stop>
                  <el-button size="small" text>
                    <el-icon>
                      <MoreFilled />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="download">下载</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 列表视图 -->
          <div v-if="viewMode === 'list'" class="documents-list">
            <el-table :data="filteredDocuments" style="width: 100%">
              <el-table-column prop="name" label="文档名称" min-width="200">
                <template #default="{ row }">
                  <div class="doc-name-cell" @click="openDocument(row)">
                    <el-icon>
                      <Document />
                    </el-icon>
                    <span>{{ row.name }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="200" />
              <el-table-column prop="updatedAt" label="更新时间" width="150">
                <template #default="{ row }">
                  {{ formatTime(row.updatedAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="size" label="大小" width="100">
                <template #default="{ row }">
                  {{ formatSize(row.size) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button size="small" text @click="toggleFavorite(row)">
                    <el-icon>
                      <Star v-if="!row.isFavorite" />
                      <StarFilled v-else />
                    </el-icon>
                  </el-button>
                  <el-dropdown @command="(command) => handleDocCommand(command, row)">
                    <el-button size="small" text>
                      <el-icon>
                        <MoreFilled />
                      </el-icon>
                    </el-button>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="edit">编辑</el-dropdown-item>
                        <el-dropdown-item command="download">下载</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <div v-if="filteredDocuments.length === 0" class="empty-state">
            <el-icon size="48">
              <Document />
            </el-icon>
            <p>暂无文档</p>
            <el-button type="primary" @click="showCreateDocDialog = true">创建第一个文档</el-button>
          </div>
        </div>

        <!-- 文档详情视图 -->
        <div v-if="selectedDocument" class="document-detail">
          <div class="doc-header">
            <div class="doc-title">
              <el-button text @click="selectedDocument = null">
                <el-icon>
                  <ArrowLeft />
                </el-icon>
              </el-button>
              <h2>{{ selectedDocument.name }}</h2>
            </div>
            <div class="doc-actions">
              <el-button @click="editDocument(selectedDocument)">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button @click="toggleFavorite(selectedDocument)">
                <el-icon>
                  <Star v-if="!selectedDocument.isFavorite" />
                  <StarFilled v-else />
                </el-icon>
                {{ selectedDocument.isFavorite ? '取消收藏' : '收藏' }}
              </el-button>
            </div>
          </div>
          <div class="doc-content">
            <div class="doc-meta-info">
              <p><strong>描述：</strong>{{ selectedDocument.description || '暂无描述' }}</p>
              <p><strong>创建时间：</strong>{{ formatTime(selectedDocument.createdAt) }}</p>
              <p><strong>更新时间：</strong>{{ formatTime(selectedDocument.updatedAt) }}</p>
              <p><strong>文档大小：</strong>{{ formatSize(selectedDocument.size) }}</p>
            </div>
            <div class="doc-body">
              <p>{{ selectedDocument.content || '文档内容为空' }}</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建文档对话框 -->
    <el-dialog v-model="showCreateDocDialog" title="新建文档" width="500px">
      <el-form :model="newDocument" :rules="docRules" ref="docFormRef" label-width="80px">
        <el-form-item label="文档名称" prop="name">
          <el-input v-model="newDocument.name" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档类型" prop="type">
          <el-select v-model="newDocument.type" placeholder="请选择文档类型">
            <el-option label="Markdown" value="markdown" />
            <el-option label="文本文档" value="text" />
          </el-select>
        </el-form-item>
        <el-form-item label="存放位置">
          <el-cascader v-model="newDocument.folderId" :options="folderOptions"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }"
            placeholder="选择存放位置（默认为根目录）" clearable filterable />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newDocument.description" type="textarea" placeholder="请输入文档描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateDocDialog = false">取消</el-button>
        <el-button type="primary" @click="createDocument">创建</el-button>
      </template>
    </el-dialog>

    <!-- 创建文件夹对话框 -->
    <el-dialog v-model="showCreateFolderDialog" title="新建文件夹" width="500px">
      <el-form :model="newFolderForm" ref="folderFormRef" label-width="80px">
        <el-form-item label="文件夹名" prop="name" :rules="[{ required: true, message: '请输入文件夹名称', trigger: 'blur' }]">
          <el-input v-model="newFolderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newFolderForm.description" type="textarea" :rows="3" placeholder="请输入文件夹描述（可选）" />
        </el-form-item>
        <el-form-item label="父文件夹">
          <el-cascader v-model="newFolderForm.parentFolderId" :options="folderOptions"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }" placeholder="选择父文件夹（可选）"
            clearable filterable />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showCreateFolderDialog = false">取消</el-button>
          <el-button type="primary" @click="handleCreateFolder">创建</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 上传文档对话框 -->
    <el-dialog v-model="showUploadDialog" title="上传文档" width="500px">
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="80px">
        <el-form-item label="目标文件夹">
          <el-cascader v-model="uploadForm.parentFolderId" :options="folderOptions"
            :props="{ value: 'id', label: 'name', children: 'children', checkStrictly: true }" placeholder="选择目标文件夹（可选）"
            clearable filterable />
        </el-form-item>
        <el-form-item label="选择文件" prop="file">
          <el-upload ref="uploadRef" :auto-upload="false" :on-change="handleFileChange" :on-remove="handleFileRemove"
            :file-list="fileList" accept=".md,.txt,.docx,.pdf" drag multiple>
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                支持 .md, .txt, .docx, .pdf 格式文件
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadDialog = false">取消</el-button>
        <el-button type="primary" @click="uploadDocuments" :loading="uploading">上传</el-button>
      </template>
    </el-dialog>

    <!-- 编辑文档对话框 -->
    <el-dialog v-model="showEditDocDialog" title="文档基本信息" width="800px">
      <el-form :model="editDocument" :rules="docRules" ref="editDocFormRef" label-width="80px">
        <el-form-item label="文档名称" prop="name">
          <el-input v-model="editDocument.name" placeholder="请输入文档名称" />
        </el-form-item>
        <el-form-item label="文档类型" prop="type">
          <el-select v-model="editDocument.type" placeholder="请选择文档类型">
            <el-option label="Markdown" value="markdown" />
            <el-option label="文本文档" value="text" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editDocument.description" type="textarea" placeholder="请输入文档描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditDocDialog = false">取消</el-button>
        <el-button type="primary" @click="updateDocument">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑空间对话框 -->
    <el-dialog v-model="showEditSpaceDialog" title="编辑空间" width="500px">
      <el-form :model="editSpace" :rules="spaceRules" ref="editSpaceFormRef" label-width="80px">
        <el-form-item label="所属" prop="scopeType">
          <el-select v-model="editSpace.scopeType" placeholder="请选择所属">
            <el-option label="团队" value="team" />
            <el-option label="个人" value="personal" />
          </el-select>
        </el-form-item>
        <el-form-item label="空间名称" prop="name">
          <el-input v-model="editSpace.name" placeholder="请输入空间名称" />
        </el-form-item>
        <el-form-item label="可见范围" prop="visibility">
          <el-select v-model="editSpace.visibility" placeholder="请选择可见范围">
            <el-option label="公开" value="public" />
            <el-option label="私有" value="private" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editSpace.description" type="textarea" placeholder="请输入空间描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditSpaceDialog = false">取消</el-button>
        <el-button type="primary" @click="updateSpace">保存</el-button>
      </template>
    </el-dialog>

    <!-- 高级搜索对话框 -->
    <el-dialog v-model="showAdvancedSearchDialog" title="高级搜索" width="1200px" :close-on-click-modal="false">
      <AdvancedSearch :space-id="parseInt(route.params.spaceId)" @close="showAdvancedSearchDialog = false"
        @document-selected="handleDocumentSelected" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, ArrowDown, Document, Folder, Edit, Delete, Star, StarFilled,
  Grid, List, MoreFilled, Expand, ArrowLeft, UploadFilled, FolderAdd, Upload
} from '@element-plus/icons-vue'
import { knowledgeSpaceApi, documentApi, documentFolderApi } from '@/api/knowledge'
import { useUserStore } from '@/stores/user'
import { clearExpiredCache } from '@/utils/routePreloader'
import AdvancedSearch from './AdvancedSearch.vue'

// 获取当前登录用户信息
const getCurrentUser = () => {
  try {
    // 优先从Pinia store获取用户信息
    if (userStore.user && userStore.user.username) {
      return userStore.user.username
    }

    // 如果store中没有，尝试从localStorage获取
    const userInfo = JSON.parse(localStorage.getItem('system-user') || '{}')
    const username = userInfo?.name || userInfo?.username

    if (username && username.trim() !== '') {
      // 将用户信息同步到store
      userStore.setUser({
        username: username.trim(),
        email: userInfo?.email || '',
        id: userInfo?.id || null
      })
      return username.trim()
    }

    console.warn('用户信息不完整或为空:', userInfo)
    return null
  } catch (error) {
    console.error('获取用户信息失败:', error)
    return null
  }
}

const route = useRoute()
const router = useRouter()

// 响应式数据
const userStore = useUserStore()
const spaceId = computed(() => route.params.spaceId)
const searchKeyword = ref('')
const showCreateDocDialog = ref(false)
const showUploadDialog = ref(false)
const showEditDocDialog = ref(false)
const showCreateFolderDialog = ref(false)
const selectedNodeId = ref(null)
const hoveredNodeId = ref(null)
const expandedKeys = ref([])
const treeKey = ref(0)
const documentTreeRef = ref(null)
const docFormRef = ref()
const uploadFormRef = ref()
const editDocFormRef = ref()
const uploadRef = ref()
const sortBy = ref('name')
const viewMode = ref('grid')
const selectedDocument = ref(null)
const uploading = ref(false)
const fileList = ref([])
const selectedFolderId = ref(null)
const currentPath = ref('根目录')
const showEditSpaceDialog = ref(false)
const editSpaceFormRef = ref()

const space = ref({})
const documents = ref([])
const documentTree = ref([])

const editSpace = reactive({
  id: '',
  name: '',
  scopeType: 'personal',
  visibility: 'private',
  description: ''
})

const newDocument = reactive({
  name: '',
  type: 'markdown',
  description: '',
  folderId: null
})

const newFolderForm = reactive({
  name: '',
  description: '',
  parentFolderId: null
})

const uploadForm = reactive({
  parentFolderId: null,
  files: []
})

const folderOptions = ref([])
const folderFormRef = ref(null)

const spaceRules = {
  name: [
    { required: true, message: '请输入空间名称', trigger: 'blur' }
  ],
  scopeType: [
    { required: true, message: '请选择所属', trigger: 'change' }
  ],
  visibility: [
    { required: true, message: '请选择可见范围', trigger: 'change' }
  ]
}

const editDocument = reactive({
  id: '',
  name: '',
  type: 'markdown',
  description: ''
})

const docRules = {
  name: [
    { required: true, message: '请输入文档名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择文档类型', trigger: 'change' }
  ]
}

const uploadRules = {
  file: [
    { required: true, message: '请选择要上传的文件', trigger: 'change' }
  ]
}

const treeProps = {
  children: 'children',
  label: 'name'
}

// 计算属性
const filteredDocuments = computed(() => {
  let filtered = documents.value

  // 根据选中的文件夹过滤文档
  if (selectedFolderId.value !== null) {
    if (selectedFolderId.value === 'root') {
      // 显示根目录下的文档（parentFolderId为null或undefined）
      filtered = filtered.filter(doc => !doc.parentFolderId)
    } else {
      // 显示指定文件夹下的文档
      filtered = filtered.filter(doc => doc.parentFolderId === selectedFolderId.value)
    }
  }

  // 根据搜索关键词过滤
  if (searchKeyword.value) {
    filtered = filtered.filter(doc =>
      doc.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      (doc.description && doc.description.toLowerCase().includes(searchKeyword.value.toLowerCase()))
    )
  }

  // 排序
  if (sortBy.value === 'name') {
    filtered.sort((a, b) => a.name.localeCompare(b.name))
  } else if (sortBy.value === 'time') {
    filtered.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
  } else if (sortBy.value === 'size') {
    filtered.sort((a, b) => (b.size || 0) - (a.size || 0))
  }
  return filtered
})

// 数据转换函数
const convertSpaceTypeToFrontend = (spaceType) => {
  const typeMap = {
    '团队': 'team',
    '个人': 'personal'
  }
  return typeMap[spaceType] || spaceType
}

const convertVisibilityToFrontend = (visibility) => {
  const visibilityMap = {
    '公开': 'public',
    '私有': 'private',
    '团队内可见': 'private',
    '仅自己可见': 'private'
  }
  return visibilityMap[visibility] || visibility
}

const convertSpaceTypeToBackend = (spaceType) => {
  const typeMap = {
    'team': '团队',
    'personal': '个人'
  }
  return typeMap[spaceType] || spaceType
}

const convertVisibilityToBackend = (visibility, scopeType) => {
  if (visibility === 'public') {
    return '公开'
  } else if (visibility === 'private') {
    // 根据空间类型决定私有的具体含义
    return scopeType === 'team' ? '团队内可见' : '仅自己可见'
  }
  return visibility
}

// 方法
const openSpaceSettings = () => {
  // 填充编辑表单数据
  Object.assign(editSpace, {
    id: space.value.id,
    name: space.value.name,
    scopeType: space.value.scopeType,
    visibility: space.value.visibility,
    description: space.value.description || ''
  })
  showEditSpaceDialog.value = true
}

const updateSpace = async () => {
  if (!editSpaceFormRef.value) return

  try {
    await editSpaceFormRef.value.validate()

    // 获取当前用户名
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    // 调用后端API更新空间
    const spaceData = {
      spaceName: editSpace.name,
      spaceType: convertSpaceTypeToBackend(editSpace.scopeType),
      visibility: convertVisibilityToBackend(editSpace.visibility, editSpace.scopeType),
      spaceDescription: editSpace.description,
      isDeleted: false
      // 注意：不更新creatorUsername，创建者信息不应该被修改
    }

    const response = await knowledgeSpaceApi.updateSpace(editSpace.id, spaceData, currentUser)
    if (response.code === '200') {
      ElMessage.success('更新成功')
      showEditSpaceDialog.value = false

      // 清理缓存，确保获取最新数据
      clearExpiredCache()

      // 重新加载空间信息
      await loadSpace()

      // 重置表单
      Object.assign(editSpace, {
        id: '',
        name: '',
        scopeType: 'personal',
        visibility: 'private',
        description: ''
      })
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新空间失败:', error)
    ElMessage.error('更新空间失败，请稍后重试')
  }
}

const quickSearch = () => {
  // 快速搜索逻辑已在计算属性中实现
}

const showAdvancedSearchDialog = ref(false)

const openAdvancedSearch = () => {
  showAdvancedSearchDialog.value = true
}

const handleDocumentSelected = (document) => {
  showAdvancedSearchDialog.value = false
  // 跳转到文档预览页
  router.push(`/knowledge/space/${document.spaceId}/document/${document.documentId}/preview`)
}

const createFolder = async () => {
  try {
    const { value: folderName } = await ElMessageBox.prompt('请输入文件夹名称', '新建文件夹', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^.+$/,
      inputErrorMessage: '文件夹名称不能为空'
    })

    const folderData = {
      folderName: folderName,
      spaceId: route.params.spaceId,
      parentFolderId: null
    }

    console.log('创建文件夹请求数据:', folderData)
    console.log('当前用户:', getCurrentUser())

    const response = await documentFolderApi.createFolder(folderData, getCurrentUser())
    console.log('创建文件夹响应:', response)

    if (response && response.code === '200') {
      ElMessage.success('文件夹创建成功')
      await loadDocuments()
    } else {
      const errorMsg = response?.msg || response?.message || '创建文件夹失败，未知错误'
      console.error('创建文件夹失败，响应:', response)
      ElMessage.error(errorMsg)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.info('创建文件夹异常:', {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data,
        timestamp: new Date().toISOString()
      })
      
      let errorMessage = '创建文件夹失败，请稍后重试'

      if (error.response) {
        // 服务器响应了错误状态码
        const status = error.response.status
        const data = error.response.data
        
        switch (status) {
          case 400:
            errorMessage = data?.msg || '请求参数错误，请检查文件夹名称'
            break
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = data?.msg || '没有在该知识空间创建文件夹的权限'
            break
          case 404:
            errorMessage = '知识空间不存在或已被删除'
            break
          case 409:
            errorMessage = data?.msg || '文件夹名称已存在，请使用其他名称'
            break
          case 422:
            errorMessage = data?.msg || '文件夹名称格式不正确'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
          case 503:
            errorMessage = '服务暂时不可用，请稍后重试'
            break
          default:
            errorMessage = data?.msg || data?.message || `请求失败 (${status})`
        }
      } else if (error.request) {
        // 请求已发出但没有收到响应
        if (error.code === 'ECONNABORTED') {
          errorMessage = '请求超时，请检查网络连接后重试'
        } else if (error.code === 'ERR_NETWORK') {
          errorMessage = '网络连接失败，请检查网络设置'
        } else {
          errorMessage = '网络连接失败，请检查网络连接'
        }
      } else {
        // 其他错误
        errorMessage = `请求配置错误: ${error.message}`
      }

      ElMessage.error(errorMessage)
    }
  }
}

const refreshTree = async () => {
  await loadDocuments()
  // 刷新后自动收起目录
  collapseAll()
  ElMessage.success('刷新成功')
}

const collapseAll = () => {
  expandedKeys.value = []
  treeKey.value++

  // 使用nextTick确保DOM更新后再设置收起状态
  nextTick(() => {
    if (documentTreeRef.value && documentTreeRef.value.store) {
      // 收起所有节点
      Object.values(documentTreeRef.value.store.nodesMap).forEach(node => {
        if (node.expanded) {
          node.collapse()
        }
      })
    }
  })
}

const handleNodeExpand = (data, node) => {
  // 由于使用了key强制刷新，这里不需要手动维护expandedKeys
}

const handleNodeCollapse = (data, node) => {
  // 由于使用了key强制刷新，这里不需要手动维护expandedKeys
}

const handleNodeRightClick = (event, data) => {
  // 右键菜单逻辑
  event.preventDefault()
}

const handleNodeDrop = (draggingNode, dropNode, dropType) => {
  ElMessage.info('拖拽功能开发中')
}

const allowDrop = (draggingNode, dropNode, type) => {
  return true
}

const allowDrag = (draggingNode) => {
  return !draggingNode.data.isRoot
}

const handleNodeAction = (command) => {
  const { action, data } = command
  switch (action) {
    case 'addFolder':
      createSubFolder(data)
      break
    case 'addDocument':
      createDocumentInFolder(data)
      break
    case 'copy':
      ElMessage.info(`复制: ${data.name}`)
      break
    case 'move':
      ElMessage.info(`移动: ${data.name}`)
      break
    case 'favorite':
      toggleFavorite(data)
      break
    case 'share':
      ElMessage.info(`分享: ${data.name}`)
      break
    case 'download':
      downloadDocument(data)
      break
  }
}

const createSubFolder = async (parentFolder) => {
  try {
    const { value: folderName } = await ElMessageBox.prompt('请输入文件夹名称', '新建子文件夹', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /^.+$/,
      inputErrorMessage: '文件夹名称不能为空'
    })

    const folderData = {
      folderName: folderName,
      spaceId: route.params.spaceId,
      parentFolderId: parentFolder.id
    }

    const response = await documentFolderApi.createFolder(folderData, getCurrentUser())
    if (response.code === '200') {
      ElMessage.success('子文件夹创建成功')
      await loadDocuments()
    } else {
      ElMessage.error(response.msg || '创建子文件夹失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.info('创建子文件夹异常:', {
        error: error.message,
        status: error.response?.status,
        data: error.response?.data,
        timestamp: new Date().toISOString()
      })
      
      let errorMessage = '创建子文件夹失败，请稍后重试'

      if (error.response) {
        const status = error.response.status
        const data = error.response.data
        
        switch (status) {
          case 400:
            errorMessage = data?.msg || '请求参数错误，请检查文件夹名称'
            break
          case 401:
            errorMessage = '登录已过期，请重新登录'
            break
          case 403:
            errorMessage = data?.msg || '没有在该知识空间创建文件夹的权限'
            break
          case 404:
            errorMessage = '父文件夹不存在或已被删除'
            break
          case 409:
            errorMessage = data?.msg || '文件夹名称已存在，请使用其他名称'
            break
          case 422:
            errorMessage = data?.msg || '文件夹名称格式不正确'
            break
          case 500:
            errorMessage = '服务器内部错误，请稍后重试'
            break
          case 503:
            errorMessage = '服务暂时不可用，请稍后重试'
            break
          default:
            errorMessage = data?.msg || data?.message || `请求失败 (${status})`
        }
      } else if (error.request) {
        if (error.code === 'ECONNABORTED') {
          errorMessage = '请求超时，请检查网络连接后重试'
        } else if (error.code === 'ERR_NETWORK') {
          errorMessage = '网络连接失败，请检查网络设置'
        } else {
          errorMessage = '网络连接失败，请检查网络连接'
        }
      } else {
        errorMessage = `请求配置错误: ${error.message}`
      }

      ElMessage.error(errorMessage)
    }
  }
}

const createDocumentInFolder = (folder) => {
  // 设置目标文件夹并打开创建文档对话框
  newDocument.folderId = folder.id
  showCreateDocDialog.value = true
}

const handleCreateFolder = async () => {
  if (!folderFormRef.value) return

  try {
    await folderFormRef.value.validate()

    const folderData = {
      folderName: newFolderForm.name,
      folderDescription: newFolderForm.description,
      spaceId: route.params.spaceId,
      parentFolderId: newFolderForm.parentFolderId
    }

    const response = await documentFolderApi.createFolder(folderData, userStore.user.username)
    if (response.code === '200') {
      ElMessage.success('文件夹创建成功')
      showCreateFolderDialog.value = false
      // 重置表单
      Object.assign(newFolderForm, {
        name: '',
        description: '',
        parentFolderId: null
      })
      await loadFolderTree()
      await loadDocuments()
    } else {
      ElMessage.error(response.msg || '创建文件夹失败')
    }
  } catch (error) {
    console.info('创建文件夹异常:', {
      error: error.message,
      status: error.response?.status,
      data: error.response?.data,
      timestamp: new Date().toISOString()
    })
    
    let errorMessage = '创建文件夹失败，请稍后重试'

    if (error.response) {
      const status = error.response.status
      const data = error.response.data
      
      switch (status) {
        case 400:
          errorMessage = data?.msg || '请求参数错误，请检查文件夹名称'
          break
        case 401:
          errorMessage = '登录已过期，请重新登录'
          break
        case 403:
          errorMessage = data?.msg || '没有在该知识空间创建文件夹的权限'
          break
        case 404:
          errorMessage = '知识空间不存在或已被删除'
          break
        case 409:
          errorMessage = data?.msg || '文件夹名称已存在，请使用其他名称'
          break
        case 422:
          errorMessage = data?.msg || '文件夹名称格式不正确'
          break
        case 500:
          errorMessage = '服务器内部错误，请稍后重试'
          break
        case 503:
          errorMessage = '服务暂时不可用，请稍后重试'
          break
        default:
          errorMessage = data?.msg || data?.message || `请求失败 (${status})`
      }
    } else if (error.request) {
      if (error.code === 'ECONNABORTED') {
        errorMessage = '请求超时，请检查网络连接后重试'
      } else if (error.code === 'ERR_NETWORK') {
        errorMessage = '网络连接失败，请检查网络设置'
      } else {
        errorMessage = '网络连接失败，请检查网络连接'
      }
    } else {
      errorMessage = `请求配置错误: ${error.message}`
    }

    ElMessage.error(errorMessage)
  }
}

const buildFolderOptions = (folders, level = 0) => {
  const options = []
  folders.forEach(folder => {
    if (folder.type === 'folder') {
      const option = {
        id: folder.id,
        name: folder.name,
        children: []
      }
      if (folder.children && folder.children.length > 0) {
        option.children = buildFolderOptions(folder.children, level + 1)
      }
      options.push(option)
    }
  })
  return options
}





const expandAll = () => {
  if (documentTree.value && documentTree.value.length > 0) {
    const getAllNodeKeys = (nodes) => {
      let keys = []
      nodes.forEach(node => {
        keys.push(node.id)
        if (node.children && node.children.length > 0) {
          keys = keys.concat(getAllNodeKeys(node.children))
        }
      })
      return keys
    }
    const allKeys = getAllNodeKeys(documentTree.value)
    expandedKeys.value = allKeys
    treeKey.value++

    // 使用nextTick确保DOM更新后再设置展开状态
    nextTick(() => {
      if (documentTreeRef.value) {
        allKeys.forEach(key => {
          documentTreeRef.value.store.nodesMap[key] && documentTreeRef.value.store.nodesMap[key].expand()
        })
      }
    })
  }
}

const handleNodeClick = (data) => {
  if (data.type === 'document') {
    openDocument(data)
  } else if (data.type === 'folder') {
    // 点击文件夹时，设置选中的文件夹ID并更新路径
    if (data.isRoot) {
      // 点击根目录
      selectedFolderId.value = null
      currentPath.value = '根目录'
      selectedNodeId.value = 'folder_root'
    } else {
      // 点击普通文件夹
      selectedFolderId.value = data.id
      updateCurrentPath(data)
      selectedNodeId.value = 'folder_' + data.id
    }
  }
}

const openDocument = (doc) => {
  // 跳转到文档预览页面
  console.log('打开文档，doc对象:', doc)
  router.push(`/knowledge/space/${spaceId.value}/document/${doc.id}/preview`)
}

// 更新当前路径
const updateCurrentPath = (folderData) => {
  if (folderData.id === 'root') {
    currentPath.value = '根目录'
  } else {
    // 构建路径：根目录/文件夹名
    currentPath.value = `根目录/${folderData.name}`
  }
}

// 获取当前文件夹名称
const getCurrentFolderName = () => {
  if (!selectedFolderId.value || selectedFolderId.value === 'root') {
    return ''
  }

  // 从文档树中查找当前选中的文件夹
  const findFolder = (nodes, targetId) => {
    for (const node of nodes) {
      if (node.id === targetId) {
        return node.name
      }
      if (node.children && node.children.length > 0) {
        const found = findFolder(node.children, targetId)
        if (found) return found
      }
    }
    return null
  }

  return findFolder(documentTree.value, selectedFolderId.value) || '未知文件夹'
}

// 导航到指定文件夹
const goToFolder = (folderId) => {
  if (folderId === 'root') {
    selectedFolderId.value = null
    currentPath.value = '根目录'
    selectedNodeId.value = 'folder_root'
  } else {
    selectedFolderId.value = folderId
    // 查找文件夹数据并更新路径
    const findFolderData = (nodes, targetId) => {
      for (const node of nodes) {
        if (node.id === targetId) {
          return node
        }
        if (node.children && node.children.length > 0) {
          const found = findFolderData(node.children, targetId)
          if (found) return found
        }
      }
      return null
    }

    const folderData = findFolderData(documentTree.value, folderId)
    if (folderData) {
      updateCurrentPath(folderData)
      selectedNodeId.value = 'folder_' + folderId
    }
  }
}

const editDocumentAction = (doc) => {
  // 填充编辑表单数据
  editDocument.id = doc.id
  editDocument.name = doc.name
  editDocument.type = doc.type
  editDocument.description = doc.description || ''
  showEditDocDialog.value = true
}

const deleteDocument = async (doc) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除文档 "${doc.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await documentApi.deleteDocument(doc.id, getCurrentUser())
    if (response.code === '200') {
      documents.value = documents.value.filter(d => d.id !== doc.id)
      ElMessage.success('删除成功')
      // 重新加载文档树
      await loadDocuments()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文档失败:', error)
      ElMessage.error('删除文档失败，请稍后重试')
    }
  }
}

// 加载收藏状态
const loadFavoriteStatus = async () => {
  try {
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      console.warn('无法获取当前用户信息，跳过加载收藏状态')
      return
    }

    const response = await documentApi.getFavoriteDocuments(currentUser)
    if (response.code === '200') {
      const favoriteDocIds = new Set(response.data.map(item => item.documentId))

      // 更新文档的收藏状态
      documents.value.forEach(doc => {
        doc.isFavorite = favoriteDocIds.has(doc.id)
      })

      console.log('收藏状态加载完成')
    } else {
      console.error('加载收藏状态失败:', response.msg)
    }
  } catch (error) {
    console.error('加载收藏状态失败:', error)
  }
}

const toggleFavorite = async (doc) => {
  try {
    const currentUser = getCurrentUser()
    if (!currentUser || currentUser.trim() === '') {
      ElMessage.error('无法获取当前用户信息，请重新登录')
      return
    }

    if (doc.isFavorite) {
      const response = await documentApi.removeFromFavorites(doc.id, currentUser)
      if (response.code === '200') {
        doc.isFavorite = false
        ElMessage.success('已取消收藏')
      } else {
        ElMessage.error(response.msg || '取消收藏失败')
      }
    } else {
      const response = await documentApi.addToFavorites(doc.id, currentUser)
      if (response.code === '200') {
        doc.isFavorite = true
        ElMessage.success('已收藏')
      } else {
        ElMessage.error(response.msg || '收藏失败')
      }
    }
  } catch (error) {
    console.error('操作收藏失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

const handleDocCommand = (command, doc) => {
  switch (command) {
    case 'edit':
      editDocumentAction(doc)
      break
    case 'download':
      downloadDocument(doc)
      break
    case 'delete':
      deleteDocument(doc)
      break
  }
}

const formatTime = (timestamp) => {
  if (!timestamp) return ''
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  // 小于1小时
  else if (diff < 60 * 60 * 1000) {
    const minutes = Math.floor(diff / (60 * 1000))
    return `${minutes}分钟前`
  }
  // 小于1天
  else if (diff < 24 * 60 * 60 * 1000) {
    const hours = Math.floor(diff / (60 * 60 * 1000))
    return `${hours}小时前`
  }
  // 小于30天
  else if (diff < 30 * 24 * 60 * 60 * 1000) {
    const days = Math.floor(diff / (24 * 60 * 60 * 1000))
    return `${days}天前`
  }
  // 小于12个月
  else if (diff < 365 * 24 * 60 * 60 * 1000) {
    const months = Math.floor(diff / (30 * 24 * 60 * 60 * 1000))
    return `${months}个月前`
  }
  // 超过1年
  else {
    const years = Math.floor(diff / (365 * 24 * 60 * 60 * 1000))
    return `${years}年前`
  }
}

const formatSize = (bytes) => {
  if (!bytes) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const loadSpace = async () => {
  const currentSpaceId = route.params.spaceId
  try {
    const response = await knowledgeSpaceApi.getSpaceById(currentSpaceId, getCurrentUser())
    if (response.code === '200') {
      const frontendScopeType = convertSpaceTypeToFrontend(response.data.spaceType)
      space.value = {
        id: response.data.spaceId,
        name: response.data.spaceName,
        description: response.data.spaceDescription,
        scopeType: frontendScopeType,
        visibility: convertVisibilityToFrontend(response.data.visibility),
        color: getSpaceColor(frontendScopeType), // 使用转换后的类型生成颜色
        members: 5 // 暂时固定值，后续可以从成员表获取
      }
    } else {
      ElMessage.error(response.msg || '加载空间失败')
      router.push('/knowledge')
    }
  } catch (error) {
    console.error('加载空间失败:', error)
    ElMessage.error('加载空间失败，请稍后重试')
    router.push('/knowledge')
  }
}

// 根据空间类型生成颜色
const getSpaceColor = (spaceType) => {
  const colors = {
    'team': '#409EFF',
    'personal': '#67C23A'
  }
  return colors[spaceType] || '#409EFF'
}

const loadDocuments = async () => {
  try {
    const documentSpaceId = route.params.spaceId
    const currentUser = getCurrentUser()

    // 检查用户信息
    if (!currentUser) {
      console.error('加载文档失败: 用户未登录或用户信息无效')
      ElMessage.error('请先登录')
      return
    }

    console.log('正在加载文档和文件夹，空间ID:', documentSpaceId, '用户:', currentUser)

    // 同时加载文档和文件夹
    const [documentsResponse, foldersResponse] = await Promise.all([
      documentApi.getDocumentsBySpace(documentSpaceId, currentUser),
      documentFolderApi.getFoldersBySpace(documentSpaceId, currentUser)
    ])

    if (documentsResponse.code === '200') {
      documents.value = documentsResponse.data.map(doc => ({
        id: doc.documentId,
        name: doc.documentName,
        description: doc.documentDescription,
        type: doc.documentType,
        size: doc.fileSize || 0,
        createdAt: new Date(doc.createdAt).getTime(),
        updatedAt: new Date(doc.updatedAt).getTime(),
        isFavorite: false, // 将在loadFavoriteStatus中设置
        content: doc.content || '',
        createdBy: doc.creatorUsername,
        parentFolderId: doc.parentFolderId
      }))
      console.log('文档加载成功，共', documents.value.length, '个文档')
    } else {
      console.error('加载文档失败:', documentsResponse.msg)
      documents.value = []
    }

    // 处理文件夹数据
    let folders = []
    if (foldersResponse && foldersResponse.code === '200') {
      folders = foldersResponse.data.map(folder => ({
        id: folder.folderId,
        name: folder.folderName,
        type: 'folder',
        parentFolderId: folder.parentFolderId,
        createdAt: new Date(folder.createdAt).getTime(),
        updatedAt: new Date(folder.updatedAt).getTime(),
        children: []
      }))
      console.log('文件夹加载成功，共', folders.length, '个文件夹')
    } else {
      console.error('加载文件夹失败:', foldersResponse?.msg || '未知错误')
    }

    // 构建文件夹层级结构
    const buildFolderTree = (folders, parentId = null) => {
      return folders
        .filter(folder => folder.parentFolderId === parentId)
        .map(folder => ({
          ...folder,
          children: [
            ...buildFolderTree(folders, folder.id), // 子文件夹
            ...documents.value.filter(doc => doc.parentFolderId === folder.id).map(doc => ({ ...doc, type: 'document' })) // 该文件夹下的文档
          ]
        }))
    }

    // 构建文档树，包含文件夹和文档
    const rootChildren = [
      ...buildFolderTree(folders), // 根级文件夹及其子结构
      ...documents.value.filter(doc => !doc.parentFolderId).map(doc => ({ ...doc, type: 'document' })) // 根级文档
    ]

    documentTree.value = [
      {
        id: 'root',
        name: '根目录',
        type: 'folder',
        isRoot: true,
        children: rootChildren
      }
    ]

    console.log('文档树构建完成，根目录包含', rootChildren.length, '个项目')

    // 加载收藏状态
    await loadFavoriteStatus()
  } catch (error) {
    console.error('加载文档和文件夹失败:', error)
    ElMessage.error('加载失败: ' + (error.message || '请求失败'))
  }
}

const createDocument = async () => {
  if (!docFormRef.value) return

  try {
    await docFormRef.value.validate()

    // 处理级联选择器返回的数组格式
    let parentFolderId = null
    if (newDocument.folderId && Array.isArray(newDocument.folderId)) {
      // 级联选择器返回数组，取最后一个值作为父文件夹ID
      parentFolderId = newDocument.folderId[newDocument.folderId.length - 1]
    } else if (newDocument.folderId) {
      // 如果不是数组，直接使用
      parentFolderId = newDocument.folderId
    }

    const documentData = {
      documentName: newDocument.name,
      documentType: newDocument.type,
      documentDescription: newDocument.description,
      spaceId: route.params.spaceId,
      parentFolderId: parentFolderId,
      content: ''
    }

    console.log('创建文档请求数据:', documentData)

    const response = await documentApi.createDocument(documentData, getCurrentUser())
    if (response.code === '200') {
      ElMessage.success('创建成功')
      showCreateDocDialog.value = false

      // 重置表单
      Object.assign(newDocument, {
        name: '',
        type: 'markdown',
        description: '',
        folderId: null
      })

      // 重新加载文档列表
      await loadDocuments()
    } else {
      ElMessage.error(response.msg || '创建失败')
    }
  } catch (error) {
    console.error('创建文档失败:', error)
    ElMessage.error('创建文档失败，请稍后重试')
  }
}

// 处理文件选择
const handleFileChange = (file, fileList) => {
  uploadForm.files = fileList
}

// 处理文件移除
const handleFileRemove = (file, fileList) => {
  uploadForm.files = fileList
}

// 上传文档
const uploadDocuments = async () => {
  if (uploadForm.files.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }

  uploading.value = true
  let successCount = 0
  let failCount = 0

  try {
    for (const file of uploadForm.files) {
      try {
        // 处理父文件夹ID
        let parentFolderId = null
        if (uploadForm.parentFolderId && Array.isArray(uploadForm.parentFolderId)) {
          parentFolderId = uploadForm.parentFolderId[uploadForm.parentFolderId.length - 1]
        } else if (uploadForm.parentFolderId && uploadForm.parentFolderId !== 'root') {
          parentFolderId = uploadForm.parentFolderId
        }

        // 调用上传API
        const response = await documentApi.uploadDocument(
          file.raw || file,
          space.value.id,
          getCurrentUser(),
          parentFolderId,
          `上传的${file.name}文件`
        )

        if (response.code === '200') {
          successCount++
        } else {
          failCount++
          console.error(`上传文件 ${file.name} 失败:`, response.msg)
        }
      } catch (error) {
        failCount++
        console.error(`上传文件 ${file.name} 失败:`, error)
      }
    }

    // 重置表单
    uploadForm.files = []
    fileList.value = []
    uploadForm.parentFolderId = 'root'
    showUploadDialog.value = false

    // 重新加载文档列表
    await loadDocuments()

    // 显示结果消息
    if (successCount > 0 && failCount === 0) {
      ElMessage.success(`成功上传 ${successCount} 个文件`)
    } else if (successCount > 0 && failCount > 0) {
      ElMessage.warning(`成功上传 ${successCount} 个文件，失败 ${failCount} 个文件`)
    } else {
      ElMessage.error('所有文件上传失败')
    }
  } catch (error) {
    console.error('上传文档失败:', error)
    ElMessage.error('上传失败')
  } finally {
    uploading.value = false
  }
}

// 根据文件名获取文档类型
const getFileType = (fileName) => {
  const ext = fileName.split('.').pop().toLowerCase()
  switch (ext) {
    case 'md':
      return 'markdown'
    case 'txt':
      return 'text'
    case 'docx':
      return 'word'
    case 'pdf':
      return 'pdf'
    default:
      return 'other'
  }
}

// 更新文档
const updateDocument = async () => {
  try {
    await editDocFormRef.value.validate()

    const documentData = {
      documentName: editDocument.name,
      documentType: editDocument.type,
      documentDescription: editDocument.description
    }

    const response = await documentApi.updateDocument(editDocument.id, documentData, getCurrentUser())
    if (response.code === '200') {
      // 重置表单
      Object.assign(editDocument, {
        id: '',
        name: '',
        type: 'markdown',
        description: ''
      })

      showEditDocDialog.value = false
      ElMessage.success('文档更新成功')

      // 重新加载文档列表
      await loadDocuments()
    } else {
      ElMessage.error(response.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新文档失败:', error)
    ElMessage.error('更新文档失败，请稍后重试')
  }
}

// 下载文档
const downloadDocument = async (doc) => {
  try {
    // 创建下载链接
    let content = ''
    let fileName = ''
    let mimeType = ''

    if (doc.type === 'markdown' || doc.type === 'text') {
      // 对于markdown和text文档，下载其内容
      content = doc.content || ''
      fileName = `${doc.name}.${doc.type === 'markdown' ? 'md' : 'txt'}`
      mimeType = 'text/plain;charset=utf-8'

      // 创建Blob对象
      const blob = new Blob([content], { type: mimeType })
      const url = window.URL.createObjectURL(blob)

      // 创建下载链接
      const link = document.createElement('a')
      link.href = url
      link.download = fileName
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)

      ElMessage.success(`文档 "${doc.name}" 下载成功`)
    } else {
      // 对于其他类型的文档（docx, pdf等），提示用户
      ElMessage.info(`文档 "${doc.name}" 是${doc.type}格式，请联系管理员获取原始文件`)
    }
  } catch (error) {
    console.error('下载文档失败:', error)
    ElMessage.error('下载文档失败，请稍后重试')
  }
}

// 生命周期
onMounted(async () => {
  await loadSpace()
  await loadDocuments()
  // 构建文件夹选项
  folderOptions.value = buildFolderOptions(documentTree.value)
  // 默认选中根目录
  selectedFolderId.value = null
  currentPath.value = '根目录'
  selectedNodeId.value = 'folder_root'
})
</script>

<style scoped>
.space-detail-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

.header-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 300px;
  background: white;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}

.space-info {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
}

.space-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  font-size: 20px;
  margin-right: 12px;
}

.space-details h3 {
  margin: 0 0 4px 0;
  color: #333;
}

.space-details p {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.space-stats {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #999;
}

.doc-tree {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.tree-header h4 {
  margin: 0;
  color: #303133;
  font-weight: 600;
}

.tree-actions {
  display: flex;
  gap: 8px;
}

.tree-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
}

.search-input {
  width: 300px;
  margin-right: 12px;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doc-tree-component {
  border: none;
}

.tree-node {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 6px 8px;
  border-radius: 6px;
  transition: all 0.3s;
  cursor: pointer;
  position: relative;
}

.tree-node:hover {
  background-color: #f0f9ff;
}

.tree-node.is-selected {
  background-color: #e1f3ff;
}

.node-icon {
  flex-shrink: 0;
  font-size: 16px;
}

.folder-icon {
  color: #f7ba2a;
}

.document-icon {
  color: #409eff;
}

.node-label {
  flex: 1;
  font-size: 14px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  min-width: 0;
}

.node-actions {
  display: flex;
  gap: 2px;
  opacity: 0;
  transition: opacity 0.3s;
  flex-shrink: 0;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.node-actions .el-button {
  padding: 2px 4px;
  min-height: auto;
  border: none;
  background: transparent;
}

.node-actions .el-button:hover {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.content-area {
  flex: 1;
  overflow-y: auto;
}

.documents-view {
  padding: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.current-path-text {
  font-size: 14px;
  color: #666;
}

.breadcrumb-clickable {
  cursor: pointer;
  color: inherit;
}

.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-header h3 {
  margin: 0;
  color: #333;
}

.view-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.documents-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.doc-card {
  background: white;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
  border: 1px solid #e8e8e8;
  position: relative;
}

.doc-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.doc-icon {
  font-size: 32px;
  color: #409EFF;
  margin-bottom: 12px;
}

.doc-info h4 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.doc-desc {
  color: #666;
  font-size: 14px;
  margin: 0 0 12px 0;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.doc-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #999;
}

.doc-actions {
  position: absolute;
  top: 12px;
  right: 12px;
  display: none;
  gap: 4px;
}

.doc-card:hover .doc-actions {
  display: flex;
}

.documents-list {
  background: white;
  border-radius: 8px;
  padding: 16px;
}

.doc-name-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.doc-name-cell .el-icon {
  margin-right: 8px;
  color: #409EFF;
}

.document-detail {
  background: white;
  margin: 24px;
  border-radius: 8px;
  overflow: hidden;
}

.doc-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px;
  border-bottom: 1px solid #e8e8e8;
}

.doc-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.doc-title h2 {
  margin: 0;
  color: #333;
}

.doc-actions {
  display: flex;
  gap: 12px;
}

.doc-content {
  padding: 24px;
}

.doc-meta-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.doc-meta-info p {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #666;
}

.doc-meta-info p:last-child {
  margin-bottom: 0;
}

.doc-body {
  line-height: 1.6;
  color: #333;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}

.empty-state .el-icon {
  margin-bottom: 16px;
}

.empty-state p {
  margin: 0 0 16px 0;
}
</style>